import React from 'react';
import _get from 'lodash/get';
import { Select, DatePicker, InputNumber, Input } from 'antd';
import CustomTreeSelectField from "components/customTreeSelectField";


const { Option } = Select;
const { TextArea } = Input;

export const defaultVariableSource = 'custom';
export const defaultFormVariableState = {
  variableSource: defaultVariableSource, // custom: 手动添加， form: 表单中选取
  formSettings: [], // [{  fieldKey, fieldName }], 当前选中表单的所有字段
  isExternalForm: 'form',
}

export const typeOptions = [
  {
    label: "字符型",
    value: "STRING",
    next: {
      key: "STRING",
      placeholder: "请输入",
      options: {},
      itemProps: { maxLength: 15 },
    },
  },
  {
    label: "布尔型",
    value: "BOOLEAN",
    next: {
      key: "bool",
      component: (
        <Select allowClear>
          <Option value="true">true</Option>
          <Option value="false">false</Option>
        </Select>
      ),
    },
  },
  {
    label: "日期时间型",
    value: "DATETIME",
    next: {
      key: "datetime",
      component: (
        <DatePicker
          allowClear
          format="YYYY-MM-DD HH:mm:ss"
          placeholder="请选择时间"
          showTime
        />
      ),
    },
  },
  {
    label: "整型",
    value: "INT",
    next: {
      key: "integer",
      component: <InputNumber precision={0} maxLength={15} allowClear />,
    },
  },
  {
    label: "浮点型",
    value: "DOUBLE",
    next: {
      key: "double",
      component: <InputNumber maxLength={20} allowClear />,
    },
  },
  {
    label: "人员",
    value: "STA",
    next: {
      key: "STA",
      component: <CustomTreeSelectField type="STA" multiple={false} />,
    },
  },
  {
    label: "组织",
    value: "ORG",
    next: {
      key: "ORG",
      component: <CustomTreeSelectField type="ORG" multiple={false} />,
    },
  },
  {
    label: "角色",
    value: "ROL",
    next: {
      key: "ROL",
      component: <CustomTreeSelectField type="ROL" multiple={false} />,
    },
  },
];

function handleProperties(fields) {
  const newArr = [];
  fields.map((item) => {
    item.fieldName = item.name;
    item.fieldKey = item.code;
    newArr.push(item);
    return newArr;
  });
  return newArr;
}

function extractAllKeys(fields) {
  const result = [];

  function dealItem(item) {
    if (!item) return;
    if (item.key && item['x-component-props']) {
      if (item['x-component-props'].enableAsFlowVariable)  {
        result.push({
          fieldName: item.title,
          fieldKey: item.key,
        });
      }
    }
    if (item.properties) {
      Object.keys(item.properties).forEach((k) => dealItem(item.properties[k]));
    }
  }

  dealItem(fields);

  return result;
}


export function getFormSettings(formId) {
  const { dispatch } = this.props;
  dispatch({
    type: "FlowHandle/isExternalForm",
    payload: { formId },
  }).then(({ errCode: _errCode, datas: _datas }) => {
    if (_errCode === 0 && _datas === true) {
      sessionStorage.setItem('isExternalForm','externalForm')
      dispatch({ type: 'FormConfigure/getExternalFormDetail', payload: { formId } })
        .then(({ errCode, errMsg, datas }) => {
        const { properties = [] } = datas;
        if (errCode !== 0) {
          this.openNotificationWithIcon(
            "warning",
            "",
            errMsg || "获取表单详细信息失败",
          );
          return;
        }
        this.setState({ formSettings: handleProperties(properties) });
      })
    } else {
      sessionStorage.setItem('isExternalForm','form')
      dispatch({ type: 'FormConfigure/getFormDetail', payload: { formId } })
      .then(({ errCode, errMsg, datas }) => {
        const { fields = {} } = datas;
        if (errCode !== 0) {
          this.openNotificationWithIcon(
            "warning",
            "",
            errMsg || "获取表单详细信息失败",
          );
          return;
        }
        // const newFileds = detailFormat(fields || []);
        this.setState({ formSettings: extractAllKeys(fields) });
      })
    }
  })
 }

export function getFormConfig() {

  const { edittingAssociatedVariable, variableSource, formSettings = [], editingIndex} = this.state;
  const { modelForms = [], loadingFormSetting } = this.props;
  const result = [
    {
      label: "添加方式",
      key: "variableSource",
      options: {
        rules: [{ required: true, message: "请选择添加方式" }],
        initialValue: defaultVariableSource,
      },
      component: (
        <Select
          disabled={edittingAssociatedVariable}
          // {...(edittingAssociatedVariable ? {title: '已关联用户任务办理人的变量不可编辑'} :{})}
          onChange={(v) => {
            this.resetForm(v);
            this.setState({ variableSource: v });
            if (v === 'form' && (!modelForms || modelForms.length === 0)) {
              this.openNotificationWithIcon(
                "warning",
                "",
                "请先关联流程/节点表单",
              );
            }
          }}
          placeholder="请选择"
        >
          <Option value="custom">
            手动添加
          </Option>
          <Option value="form">
            表单获取
          </Option>
        </Select>
      ),
    },
  ];

  if (variableSource === 'form') {
    result.push(
      {
        label: "选择表单",
        key: "formId",
        options: { rules: [{ required: true, message: "请选择表单" }] },
        component: (
          <Select
            disabled={edittingAssociatedVariable}
            // {...(edittingAssociatedVariable ? {title: '已关联用户任务办理人的变量不可编辑'} :{})}
            onChange={v => {
              // eslint-disable-next-line
              this.props.form.resetFields(['name', 'code', 'defaultValue', 'type', 'description']);
              this.setState({ formSetttings: [], selectedType: null });
              getFormSettings.call(this, v)
            }}
            placeholder="请选择"
          >
            {modelForms.filter((obj, index) =>
                modelForms.findIndex((item) => item.uuid === obj.uuid) === index
            ).map(({ formId, formName }) => (
              <Option value={formId} key={formId}>
                {formName}
              </Option>
            ))}
          </Select>
        ),
      },
      {
        label: "变量名称",
        placeholder: "请输入",
        key: "name",
        options: { rules: [{ required: true, message: "请选择变量名称" }] },
        component: (
          <Select
            disabled={edittingAssociatedVariable}
            // {...(edittingAssociatedVariable ? {title: '已关联用户任务办理人的变量不可编辑'} :{})}
            onChange={(v, option) => {
              this.props.form.setFieldsValue({
                code: option.props.fieldKey,
              });
            }}
            placeholder="请选择"
            loading={loadingFormSetting}
          >
            {formSettings.map(({ fieldKey, fieldName }) => (
              <Option value={fieldName} key={fieldKey} fieldKey={fieldKey}>
                {fieldName}
              </Option>
            ))}
          </Select>
        ),
      },
      {
        label: "变量编码",
        placeholder: "请输入",
        key: "code",
        component: (
          <Select
            disabled
            placeholder="请选择变量名称"
            style={{maxWidth: 205 }}
          >
            {formSettings.map(({ fieldKey }) => (
              <Option value={fieldKey} key={fieldKey}>
                {fieldKey}
              </Option>
            ))}
          </Select>
        ),

      },
    );
  } else {
    result.push(
      {
        label: "变量名称",
        placeholder: "请输入",
        key: "name",
        options: { rules: [{ required: true, message: "请输入变量名称" }] },
        itemProps: { maxLength: 20 },
      },
      {
        label: "变量编码",
        placeholder: "请输入",
        key: "code",
        options: {
          rules: [
            { required: true, message: "请输入变量编码" },
            {
              pattern: /^[a-zA-Z_][a-zA-Z_0-9-.]*$/,
              message: "支持字母、数字、小数点、下划线、中划线，须以字母或者下划线开头",
            },
          ],
        },
        itemProps: { maxLength: 64 },
      },
    )
  }
  return result.concat([
    {
      label: "变量类型",
      key: "type",
      options: {
        rules: [
          { required: true, message: "请输入变量类型" },
        ],
      },
      component: (
        <Select
          disabled={edittingAssociatedVariable}
          // {...(edittingAssociatedVariable ? {title: '已关联用户任务办理人的变量类型不可编辑'} :{})}
          onChange={v => {
            // eslint-disable-next-line
            this.props.form.resetFields(["defaultValue"]);
            this.setState({ selectedType: v });
          }}
          placeholder="请选择"
        >
          {typeOptions.map(({ label, value }) => (
            <Option value={value} key={value}>
              {label}
            </Option>
          ))}
        </Select>
      ),
    },
    {
      label: "变量值来源",
      key: "variableSourceHint",
      options: {
        initialValue: defaultVariableSource,
      },
      component: (
        <Select
          disabled
          placeholder="请选择"
        >
          <Option value="custom">
            从接口获取
          </Option>
          <Option value="form">
            从表单中获取
          </Option>
        </Select>
      ),
    },
    {
      key: "defaultValue",
      label: "默认值",
      placeholder: "请输入",
      options: {},
      itemProps: { maxLength: 15, disabled: editingIndex < 0},
    },
    {
      label: "变量说明",
      placeholder: "请输入说明",
      key: "description",
      component: <TextArea placeholder="请输入说明" maxLength={100} />,
    },
  ]);

}

const walkModelNodes = (nodes, callback) => {
  if (nodes && nodes.length > 0) {
    nodes.forEach(callback)
  }
}
;
// 获取流程及其节点关联的表单
export function getModelForms(properties, nodes) {
  const result = [];// { formId, formKey, formName, isRef(是否有流程或节点变量引用此表单) }

  const refMap = {};

  const updateVarsRef = (variables) => {
    if (variables && variables.length > 0) {
      // { code, name, type, variableSource, (variableSource为form 才有: formId, formName, formKey) }
      variables.forEach((variable) => {
        if (variable.variableSource === 'form') {
          refMap[variable.formId] = true;
        }
      });
    }
  }

  const vars = properties.modelVariables || [];
  updateVarsRef(vars, properties);

  // 不用设置节点的变量
  // walkModelNodes(nodes, (node) => {
  //   vars = _get(node, 'model.properties.nodeVariables');
  //   updateVarsRef(vars);
  // });

  // 流程表单
  let {
    formId,
    formkeydefinition: formKey,
    formname: formName,
  } = properties || {};
  if (formId) {
    result.push({
      formKey,
      formId,
      formName,
      isRef: !!refMap[formId],
    })
  }

  walkModelNodes(nodes, (node) => {
    formId = _get(node, 'model.properties.formId');
    if (formId) {
      formKey = _get(node, 'model.properties.formkeydefinition');
      formName = _get(node, 'model.properties.formname');
      result.push({
        formKey,
        formId,
        formName,
        isRef: !!refMap[formId],
      })
    }
  })

  return result;
}

export function isFormReferenced(formId, modelForms) {
  return formId && (modelForms || []).some(({ formId: id, isRef }) => (formId === id && isRef))
}
